#include "head.h"

int tcpInit(char *config_file, int *psockfd)
{
    FILE *fd = fopen(config_file, "r");
    char ip[1024] = {0};
    char port[1024] = {0};
    char buf[1024] = {0};
    fgets(buf, sizeof(buf), fd);
    int i = 0;
    while (!isdigit(buf[i]))
    {
        ++i;
    }
    strcpy(ip, buf + i);
    bzero(buf, sizeof(buf));
    fgets(buf, sizeof(buf), fd);
    i = 0;
    while (!isdigit(buf[i]))
    {
        ++i;
    }
    strcpy(port, buf + i);

    *psockfd = socket(AF_INET, SOCK_STREAM, 0);
    // printf("sockfd = %d\n",*psockfd);
    // printf("port = %s\n",port);
    // printf("ip : %s\n",ip);
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(ip);
    addr.sin_port = htons(atoi(port));
    int reuse = 1;
    int ret = setsockopt(*psockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
    ERROR_CHECK(ret, -1, "setsockopt");
    ret = connect(*psockfd, (struct sockaddr *)&addr, sizeof(addr));
    ERROR_CHECK(ret, -1, "connect");
    return 0;
}
